/**
 *  JFTSTool - Java Full Text Search tool.
 *  Copyright (C) <2009>  <grupo JFTS>
 *  This program is free software: you can redistribute it and/or modify
 *	it under the terms of the GNU General Public License as published by
 *	the Free Software Foundation, either version 3 of the License, or
 *	(at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.jftstool.semantic.inference;

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import ontea.core.Pattern;
import ontea.core.PatternRegExp;
import ontea.core.PatternSet;
import ontea.core.Result;

import org.jftstool.config.SemanticConfig;
import org.jftstool.fileParserFramework.metadata.DocumentMetaData;
import org.jftstool.indexer.document.DBDocument;
import org.jftstool.semantic.ISemanticModel;
import org.jftstool.semantic.exceptions.JFTSSemanticException;
import org.xml.sax.ContentHandler;

/**
 * Class responsible for inferring what kind of ontology a document belongs.
 * @author grupo JFTS
 *
 */
public class DefaultSemClassInf implements ISemanticClassInference {
	private PatternSet pSet = null;
	private SemanticConfig config = null;
	
	public DefaultSemClassInf(SemanticConfig config){
		pSet = new PatternSet(config.getPatternFile());
		this.config = config;
	}
	
	
	@Override
	public void anotateDocument(ISemanticModel sm, DBDocument dbDoc, ContentHandler text, DocumentMetaData metaData)
				  throws JFTSSemanticException {
		
		String matchText = "";
		String metaDataValue = null;
		String classInfered = null;
		Set<Result> results = null;
		List<String> mappings = config.getClassMapping();
		String newLine = System.getProperty("line.separator");
		
		for(String s : mappings){
			metaDataValue =  metaData.getProperty(s.trim());
			if (metaDataValue != null){
				matchText = matchText + newLine + metaDataValue;				
			}
		}
	
		results = _matchPatterns(matchText);
		Iterator<Result> iResult = results.iterator();
		while (iResult.hasNext()){
			Result r = (Result)iResult.next();			
			classInfered = r.getType();
			break;
		}
		
		if (classInfered == null){
			matchText = (text.toString().length() > config.getAnalyzeMaxLength()) ? text.toString().substring(0, config.getAnalyzeMaxLength()) : text.toString();			
			
			results = _matchPatterns(matchText);
			iResult = results.iterator();
			while (iResult.hasNext()){
				Result r = (Result)iResult.next();			
				classInfered = r.getType();
				break;
			}			
			
			if (classInfered == null){
				classInfered = config.getUnknownClass();				
			}
		}
		metaData.add("ontClassPath", sm.getOntClassPath(classInfered, sm.getBaseModel()));
		String instanceName = (dbDoc == null) ? metaData.getProperty(DocumentMetaData.URI): dbDoc.getField("id").getValue().toString(); 
		sm.addNewInstance(classInfered, instanceName, true);
	}
	
	
	private Set<Result> _matchPatterns(String text) {
	    Set<Result> allResults = new HashSet<Result>();
	    
	    Iterator<Pattern> iPattern = pSet.getPatternSet().iterator();
	    while (iPattern.hasNext()) {
	      PatternRegExp p = ((PatternRegExp)iPattern.next());
	      Set<Result> sResult = p.annotate(text);
	      
	      Iterator<Result> iResult = sResult.iterator();
	      while (iResult.hasNext()){
	        Result r = (Result)iResult.next();
	        allResults.add(r);
	      }
	    }
	    
	    return allResults;
	  } 	
}